package com.application.fabric.test.Token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.Map;


@Repository
@Component
public class Token01 {
//    /**
//     * 生成 token
//     */
    public  String getToken(Map<String,String> map) {
        Date date = new Date(System.currentTimeMillis() + 86400*1000);
        Algorithm algorithm = Algorithm.HMAC256("Xinmachong666");
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        // 附带username信息
        return builder
                //到期时间
                .withExpiresAt(date)
                //创建一个新的JWT，并使用给定的算法进行标记
                .sign(algorithm);
    }
//    /**
//     * 校验 token 是否正确
//     */
    public  DecodedJWT verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256("Xinmachong666");
            return JWT.require(algorithm).build().verify(token);
        } catch (TokenExpiredException e) {
            // token已过期
            return null;
        } catch (JWTVerificationException e) {
            // token不正确
            return null;
        }
    }
}
